import { BaseLogger } from "./base_log";
const logger = new BaseLogger("base_list_scroll.ts");
export default class BaseListScroll {
  el: Element;
  touching: boolean = false;
  isTouchMoving: boolean = false;
  startX: number = 0;
  startY: number = 0;

  isCallbacking: boolean = false;
  onBottom: Function;

  constructor(el: Element, onBottom: Function) {
    this.el = el;
    this.onBottom = onBottom;
  }

  touchstart(evt: TouchEvent) {
    this.touching = true;
    this.startX = evt.targetTouches[0].pageX;
    this.startY = evt.targetTouches[0].pageY;
  }
  touchend(evt: TouchEvent) {
    this.touching = false;
    this.isTouchMoving = false;
  }
  touchmove(evt: TouchEvent) {
    if (!this.touching) return;
    //setTimeout(() => {
    this.touchmoveX(evt);
    //}, 200);
  }
  touchmoveX(evt: TouchEvent) {
    if (this.isCallbacking) return;

    //loading data,not ok yet!!
    if (!this.touching) return;
    if (!this.isScrollToBottom(evt)) {
      logger.info("bottom OK!!");
      if (this.isTouchMoving) {
        this.isTouchMoving = false;
      }
      return;
    }
    let diffY = this.diffY(evt);
    if (Math.abs(diffY) < 5) {
      this.isTouchMoving = true;
      logger.info("show more flag:1");
      return;
    }
    logger.info("show more flag:2=>diff=" + diffY);
    this.isTouchMoving = false;
    setTimeout(() => {
      this.isCallbacking = true;
      if (this.onBottom) this.onBottom();
      this.isCallbacking = false;
    }, 100);
  }
  isScrollToBottom(evt: TouchEvent) {
    const ynow: number = this.el.scrollTop || window.scrollY;
    const contentHeight: number = this.el.scrollHeight;
    const windowEleClientHeight: number = this.el.clientHeight;
    const xel: any = this.el;
    const offsetHeight: number = xel.offsetHeight;
    if (offsetHeight + ynow - contentHeight >= -1) {
      logger.info(
        "a bottom=>距顶部" +
          ynow +
          "offsetHeight" +
          offsetHeight +
          "滚动条总高度" +
          contentHeight
      );
      return true;
    }
    if (ynow + windowEleClientHeight >= contentHeight) {
      logger.info(
        "b bottom=>距顶部" +
          ynow +
          "可视区高度" +
          windowEleClientHeight +
          "滚动条总高度" +
          contentHeight
      );
      return true;
    }
    logger.info(
      "c Nbottom=>距顶部" +
        ynow +
        "offsetHeight" +
        offsetHeight +
        "滚动条总高度" +
        contentHeight +
        "可视区高度" +
        windowEleClientHeight
    );

    return false;
  }
  diffY(evt: TouchEvent): number {
    let endY = evt.changedTouches[0].pageY;
    let dy = this.startY - endY;
    return dy;
  }
  diffX(evt: TouchEvent): number {
    let endX = evt.changedTouches[0].pageX;
    let dx = this.startX - endX;
    return dx;
  }
}
